import logger from "./logger";
import { config } from '../config';
import * as Redis from 'redis';

class RedisProxy {
  _instance: RedisProxy = null;
  client: any;
  static _instance: RedisProxy;
  constructor() {
    const client = Redis.createClient({
      url: `redis://${config.redis.host}:${config.redis.port}`,
    });
    
    client.on('error', err => {
      logger.error('Redis Client Error!', err);
      process.exit(1);
    });
    
    client.connect().then(()=>{
      logger.info('Redis connected!');
    });
    this.client = client
  }

  static instance() {
    if(!this._instance) {
      const instance = new RedisProxy();
      this._instance = instance;
    }
    return this._instance;
  }
}

export async function init() {
  return RedisProxy.instance();
}

export const client = RedisProxy.instance().client;

export default {
  init,
  instance: RedisProxy.instance(),
  client: RedisProxy.instance().client
};
